<?php

namespace app\http\exception;


use Exception;
use RuntimeException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;

class HttpHandle extends Handle
{
    public function render($request, $e) : Response
    {

        if ($e instanceof HttpException) {
            $data['code'] = $e->getCode() ?: 500;
            $data['msg'] = $e->getMessage();
            $data['result'] = [];
            $data['error'] = $e->getTrace();
            return $this->returnJson($data , 500);
        }

        if ($e instanceof ValidateException) {
            $data['code'] = 406;
            $data['msg'] = $e->getMessage();
            $data['result'] = [];
            $data['error'] = $e;
            return $this->returnJson($data , 406);
        }
        if ($e instanceof AuthException) {
            $data['code'] = $e->getCode() ?? 405;
            $data['msg'] = $e->getMessage();
            $data['result'] = [];
            $data['error'] = $e;
            return $this->returnJson($data , 405);
        }
        //通过ID查询空数据异常
        if ($e instanceof ModelNotFoundException || $e instanceof DataNotFoundException) {
            $data['code'] = 407;
            $data['msg'] = '数据不存在!';
            $data['result'] = [];
            $data['error'] = $e;
            return $this->returnJson($data , 407);
        }

        if($e instanceof RuntimeException){
            $data['code'] = $e->getCode() ?: 500;
            $data['msg'] = $e->getMessage();
            $data['result'] = [];
            $data['error'] = $e->getTrace();
            return $this->returnJson($data , 500);
        }

        // 全局异常通过json返回
        if ($e instanceof Exception) {
            $data['code'] = $e->getCode() ?: 500;
            $data['msg'] = $e->getMessage();
            $data['result'] = [];
            $data['error'] = $e->getTrace();
            return $this->returnJson($data , 500);
        }
        return $this->returnJson( [
            'code'  => 400,
            'mag'   => $e->getMessage(),
            'error' => $e->getTrace()
        ] , 500);
        //可以在此交由系统处理
//        return parent::render($request, $e);
    }

    function returnJson($data , $code) : \think\response\Json
    {
        if(isset($data['error'])){
            unset($data['error']);
        }
        return json($data, $code);
    }
}
